package com.bridgeintelligent.tag.customer.service;


import com.bridgeintelligent.tag.constants.bulkload.IssueMqMsg;
import com.bridgeintelligent.tag.constants.bulkload.MQConfig;
import com.bridgeintelligent.tag.customer.entity.IssueLog;
import com.bridgeintelligent.tag.customer.entity.IssueTask;
import com.bridgeintelligent.tag.customer.mapper.IssueLogMapper;
import com.bridgeintelligent.tag.customer.mapper.IssueTaskMapper;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 下发定时任务 一天一次
 */
@AllArgsConstructor
@Component
@Slf4j
public class CustomersIssueScheduled {

    protected RocketMQTemplate rocketMQTemplate;

    private ObjectMapper objectMapper;

    private IIssueSendService issueSendService;

    private IssueTaskMapper issueTaskMapper;

    private IssueLogMapper issueLogMapper;

    @Scheduled(cron = "0 5 0 * * ?")
    public void handle() {
        log.info("---------下发失效定时开始-----------");
        try{
            int num = issueTaskMapper.updateToStop(DateHelper.currentDateTime("yyyy-MM-dd"),new Date());
            log.info("发现失效的任务配置：{}个", num);
            int tasks = issueTaskMapper.updateToStopTask(DateHelper.currentDateTime("yyyy-MM-dd"),new Date());
            log.info("发现失效的任务：{}个", tasks);
            int customersStop = issueTaskMapper.updateCustomersToStop(new Date());
            log.info("发现客群失效导致失效的任务配置：{}个", customersStop);
            int customersTaskStop = issueTaskMapper.updateCustomersToStopTask(new Date());
            log.info("发现客群失效导致失效的任务：{}个", customersTaskStop);
        } catch (Exception e){
            log.error("发现任务失效",e);
        }
        log.info("---------下发定时开始-----------");
        List<IssueTask> tasks = issueTaskMapper.findValidTasks(DateHelper.currentDateTime("yyyy-MM-dd"));
        if (CollectionUtils.isNotEmpty(tasks)) {
            for (IssueTask task : tasks) {
                try{
                    issueSendService.sendByTaskId(task.getId());
                } catch (Exception e){
                    log.error("定时",e);
                }
            }
        }
    }

    @Scheduled(cron = "0 */5 * * * ?")
    public void issue(){
        List<IssueLog> issueLogs = issueTaskMapper.findPending();
        log.info("发现正在执行的任务：{}个", issueLogs.size());
        if(CollectionUtils.isNotEmpty(issueLogs)){
            issueLogs.forEach(issueLog -> {
                try {

                    //判断如果是周下发，不判断数据日期，直接触发MQ动作
                    if (StringUtils.equals("3",issueLog.getFrequency())){
                        send(issueLog);
                    }else{
                        //通过logId查询indexId
                        String indexId = issueLogMapper.findIndexIdByTaskId(issueLog.getId());
                        if(!check(issueLog,indexId)){
                            log.debug("数据未到暂不发送{}", issueLog.getId());
                            issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId())
                                    .setUpdateTime(new Date()).setReason("数据未到暂不发送"));
                            return;
                        }
                        send(issueLog);
                    }
                } catch (JsonProcessingException e) {
                    log.error("客群下发失败：{},原因：{}",issueLog.getId(),e);
                }
            });
        }
    }

    private boolean check(IssueLog issueLog,String indexId) {
        if(issueLog.getDataDate().length()==6){
            int count = issueTaskMapper.countEs6(issueLog.getDataDate(),indexId);
            if(count<=0){
                return false;
            }
        }
        if(issueLog.getDataDate().length()==8){
            int count = issueTaskMapper.countEs8(issueLog.getDataDate(),indexId);
            if(count<=0){
                return false;
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void send(IssueLog issueLog) throws JsonProcessingException {
        if(StringUtils.isBlank(issueLog.getId())){
            return;
        }
        IssueMqMsg issueMqMsg = new IssueMqMsg();
        issueMqMsg.setId(issueLog.getId());
        String msg = objectMapper.writeValueAsString(issueMqMsg);
        rocketMQTemplate.convertAndSend(MQConfig.FILE_ISSUE_TOPIC, msg);
        issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId())
                .setState("1").setUpdateTime(new Date()).setReason("-"));
    }

    @Scheduled(cron = "0 30 7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 * * ?")
    public void updateCustomersToStop(){
        int customersStop = issueTaskMapper.updateCustomersToStop(new Date());
        log.info("发现客群失效导致失效的任务配置：{}个", customersStop);
        int customersTaskStop = issueTaskMapper.updateCustomersToStopTask(new Date());
        log.info("发现客群失效导致失效的任务：{}个", customersTaskStop);
    }
}
